package mm.chenchen.db.service;

import com.alibaba.druid.pool.DruidDataSource;
import mm.chenchen.db.cache.DynamicDataSourceCache;
import mm.chenchen.db.config.DynamicContextHolder;
import mm.chenchen.db.config.DynamicDataSource;
import mm.chenchen.db.config.DynamicDataSourceFactory;
import mm.chenchen.db.model.DataSourceCreate;
import mm.chenchen.db.properties.DataSourceProperties;
import mm.chenchen.utils.BeanUtil;
import mm.chenchen.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class DynamicDataSourceService {
    private Logger logger = LoggerFactory.getLogger(getClass());




    @Autowired
    private DynamicDataSource dynamicDataSource;


    public DynamicDataSourceService(){
        DynamicDataSourceCache.DS_TYPE.put("default","mysql");
    }

    public R addDataSource(DataSourceCreate create) {
        DynamicDataSourceCache.DS_TYPE.put(create.getDataSourceName(),create.getDbType());
        logger.info("开始新增数据源为 : {}", create.getDataSourceName());
        DataSourceProperties dataSourceProperties = new DataSourceProperties();
        BeanUtil.copyProperties(create, dataSourceProperties);
        if ("ORACLE".equalsIgnoreCase(create.getDbType())) {
            dataSourceProperties.setValidationQuery("SELECT 1 FROM DUAL");
        }
        DruidDataSource druidDataSource = DynamicDataSourceFactory.buildDruidDataSource(dataSourceProperties);
        if ("default".equalsIgnoreCase( create.getDataSourceName())) {
            return R.error("default数据源不可被覆盖,请换个名称!");
        }
        DynamicDataSourceCache.DS.put(create.getDataSourceName(), druidDataSource);
        dynamicDataSource.setTargetDataSources(DynamicDataSourceCache.DS);
        dynamicDataSource.afterPropertiesSet();
        return R.ok();
    }


    public R removeDataSource(String dataSourceName) {
        DynamicDataSourceCache.DS.remove(dataSourceName);
        dynamicDataSource.setTargetDataSources(DynamicDataSourceCache.DS);
        dynamicDataSource.afterPropertiesSet();
        return R.ok();
    }

    public R changeCurrentDataSource(String dataSourceName) {
        logger.info("切换当前数据源为 : {}", dataSourceName);
        DynamicContextHolder.push(dataSourceName);
        DynamicDataSourceCache.CURRENT_DS = dataSourceName;
        return R.ok();
    }

    public R removeCurrentDataSource() {
        DynamicContextHolder.poll();
        return R.ok();
    }

    public R dsList() {
        return R.ok().setData(DynamicDataSourceCache.DS.keySet());
    }
}
